package com.guapi.schedule;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CronTaskRegister implements DisposableBean {
    //存储定时任务
    private final Map<Runnable, ScheduleTask> scheduleTasks = new ConcurrentHashMap<>(16);

    private final Log log = LogFactory.get(CronTaskRegister.class);
    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    public void addCronTask(Runnable task, String cronExpression) {
        addCronTask(new CronTask(task, cronExpression));
    }

    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable runnable = cronTask.getRunnable();
            if (this.scheduleTasks.containsKey(runnable)) {
                removeRunTask(runnable);
            }
            //添加定时任务
            log.info("------------开启定时任务-------------");
            this.scheduleTasks.put(runnable, scheduleCronTask(cronTask));
        }
    }

    public ScheduleTask scheduleCronTask(CronTask cronTask) {
        ScheduleTask scheduleTask = new ScheduleTask();
        scheduleTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduleTask;
    }

    /**
     * 移除且取消定时任务
     *
     * @param runnable
     */
    public void removeRunTask(Runnable runnable) {
        ScheduleTask task = this.scheduleTasks.remove(runnable);
        if (task != null) {
            task.cancel();
        }
    }


    @Override
    public void destroy() throws Exception {
        //停止定时任务
        for (ScheduleTask value : this.scheduleTasks.values()) {
            value.cancel();
        }
        //清空定时任务集合
        this.scheduleTasks.clear();
    }
}
